package com.ndp.fb.mq.service.schedulerservice.business.syncbusiness;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.ndp.fb.fbagent.service.AccountFBService;
import com.ndp.fb.model.fbagent.result.entrustaccount.AccountIns;
import com.ndp.fb.mq.api.service.schedulerservice.AdAccountsSchedulerService;
import com.ndp.fb.mq.api.service.schedulerservice.business.syncbusiness.SyncAccountResourceService;
import com.ndp.fb.mq.service.schedulerservice.business.FetchCustomaudiencesService;
import com.ndp.fb.rdb.api.AccountInstagramActRdbService;
import com.ndp.fb.rdb.model.AccountInstagramAct;
import com.ndp.fb.util.ListUtil;
import com.ndp.fb.util.ThreadPool;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Elvis on 2015/4/9.
 */
@Service
public class SyncAccountResourceServiceImpl implements SyncAccountResourceService {

    private static final Logger logger = LoggerFactory.getLogger(SyncAccountResourceServiceImpl.class);

    @Autowired
    private AdAccountsSchedulerService adaccountsSchedulerService;

    @Reference
    AccountInstagramActRdbService accountInstagramActRdbService;

    @Autowired
    FetchCustomaudiencesService fetchCustomaudiencesService;

    @Reference
    AccountFBService accountFBService;

    @Override
    public void syncCustomaudiences(Long accountId, String userId) {
        ThreadPool.execute(() -> {
            try {
                fetchCustomaudiencesService.uploadCustomaudiencesByAccountId(accountId,userId);
            } catch (Exception e){
                logger.error(e.getMessage(),e);
            }
        });
    }

    //定时拉取广告账号下的ins账号
    @Override
    public void syncAccountIns(Long fbAccountId)
    {
        String token = adaccountsSchedulerService.getAdaccountsToken(fbAccountId);//CAAEJqYBYwW0BADxjnEpaABY2UxQZCsbpaiDk9fq5a8XaZANZBk7N5JlprFKhHZBVqTzaYkORNR5rcbUV0yb2oZAMJmJZAnZApVvGWXrfB2ZBL2S9GsuelGxcr89kZCPZB7gxgwOStoQnuH2BVgeugWIawe1zcZCrNf30AxVNaIv28f7FMuaSLTZAr0rrOij6lf8tLBpuZCrni1VAbH3SjFfL8gozR
        if (StringUtils.isEmpty(token)) {
            logger.warn("拉取广告账号{}下的instagram账号---->havn't token", fbAccountId);
            return;
        }
        accountFBService.syncAccountIns(token, fbAccountId);
    }

    //拉取广告账号下的ins账号callback
    public void syncAccountInsCallback(Map<String, String> equipment, Object msg)
    {
        Long fbActId = Long.valueOf(equipment.get("fbActId"));
        logger.info("拉取广告账号{}下的instagram账号callback", fbActId);
        if(StringUtils.isEmpty(msg.toString()))
            return;
        List<AccountIns> accountInsList;
        try
        {
            accountInsList = (List<AccountIns>)msg;
        }catch (Exception e)
        {
            return;
        }
        if(ListUtil.isEmpty(accountInsList))
            return;
        List<Long> insIdWe = new ArrayList<>();
        Map<Long, AccountInstagramAct> accountInstagramActMap = new HashMap<>();
        List<AccountInstagramAct> accountInstagramActList = accountInstagramActRdbService.findInsActIdsByAccountId(fbActId);
        for(AccountInstagramAct accountInstagramAct : accountInstagramActList)
        {
            insIdWe.add(accountInstagramAct.getInsAccountId());
            accountInstagramActMap.put(accountInstagramAct.getInsAccountId(), accountInstagramAct);
        }

        List<Long> insIdFb = new ArrayList<>();
        List<Long> insIdNeedDelete = new ArrayList<>();
        insIdNeedDelete.addAll(insIdWe);
        List<Long> insIdNeedUpdate = new ArrayList<>();  //是交集
        insIdNeedUpdate.addAll(insIdWe);
        Map<Long, AccountIns> accountInsMap = new HashMap<>();
        for(AccountIns accountIns : accountInsList)
        {
            insIdFb.add(accountIns.getInsAccountId());
            accountInsMap.put(accountIns.getInsAccountId(), accountIns);
        }

        List<AccountInstagramAct> accountInstagramActs = new ArrayList<>();
        //一、needUpdate  交集 需要更新到我们库中
        insIdNeedUpdate.retainAll(insIdFb);
        if(ListUtil.isNotEmpty(insIdNeedUpdate))
        {
            insIdNeedUpdate.forEach(insId -> {
                //fb上得记录跟我们库中一样就不更新  以免浪费rdb update操作
                AccountInstagramAct we = accountInstagramActMap.get(insId);
                AccountIns accountIns = accountInsMap.get(insId);
                if (we != null && StringUtils.isNotEmpty(we.getInsAccountUsername())
                        && we.getInsAccountUsername().equals(accountIns.getUsername())
                        && we.getInsAccountIsPublished() == accountIns.getInsAccountIsPublished()
                        && we.getHasProfilePic() == accountIns.getHasProfilePic()
                        && we.getInsAccountOwnerBmId().equals(accountIns.getBusinesses().getId())
                        && !we.getIsDelete()) {
                    logger.info("跟我们库中是一样的same to fb no need update");
                } else {
                    we.setInsAccountIsPublished(accountIns.getInsAccountIsPublished());
                    we.setHasProfilePic(accountIns.getHasProfilePic());
                    we.setInsAccountOwnerBmId(accountIns.getBusinesses().getId());
                    we.setInsAccountUsername(accountIns.getUsername());
                    accountInstagramActs.add(we);
                }
            });

        }

        //二、needInsert  需要插入到我们库中的
        List<Long> insIdNeedInsert = insIdFb;
        insIdNeedInsert.removeAll(insIdNeedUpdate);
        if(ListUtil.isNotEmpty(insIdNeedInsert))
        {
            insIdNeedInsert.forEach(insId -> {
                AccountInstagramAct obj = new AccountInstagramAct();
                AccountIns accountIns = accountInsMap.get(insId);
                obj.setIsDelete(false);
                obj.setInsAccountIsPublished(accountIns.getInsAccountIsPublished());
                obj.setHasProfilePic(accountIns.getHasProfilePic());
                obj.setInsAccountOwnerBmId(accountIns.getBusinesses().getId());
                obj.setFbAccountId(fbActId);
                obj.setInsAccountUsername(accountIns.getUsername());
                obj.setInsAccountId(insId);
                accountInstagramActs.add(obj);
            });
        }
        if(ListUtil.isNotEmpty(accountInstagramActs))
            accountInstagramActRdbService.batchSaveOrUpdate(accountInstagramActs);

        insIdNeedDelete.removeAll(insIdNeedUpdate);
        //三、needDelete就是我们系统多出来的，需要更新为删除
        if (ListUtil.isEmpty(insIdNeedDelete))
            return;
        accountInstagramActRdbService.updateIsDelete(insIdNeedDelete, fbActId);
    }
}
